
package com.example.cia.support;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.cia.service.Service;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;

import com.squareup.okhttp.Response;


public class HttpServiceComplicated<T> {

	/**
	 * 用于执行复杂查询、添加等的操作
	 * 使用的是http get方法。
	 */
	
	/**
	 * simple data being queried
	 */
	private T data;
	
	
	public T getData() {
		return data;
	}

	
	public void setData(T data) {
		this.data = data;
	}

	
	public Service getService() {
		return service;
	}

	
	public void setService(Service service) {
		this.service = service;
	}

	
	public String getUrl() {
		return url;
	}

	
	public void setUrl(String url) {
		this.url = url;
	}

	
	public List<String> getResult() {
		return result;
	}

	
	public void setResult(List<String> result) {
		this.result = result;
	}

	/**
	 * the host address and port,can not be changed
	 */
	private final String spaceName = "http://192.168.31.159:8080";
	
	/**
	 * the service object being used
	 */
	private Service service;

	private OkHttpClient okHttpClient;
	
	/**
	 * detailed servlet being used
	 */
	private String url;
	
	/**
	 * the result of this operation
	 */
	private List<String> result;
	
	/**
	 * according to return parameters' number,returns a result map
	 * @param num query parameters' count
	 * @return a result map
	 */
	public void doHttpPost(final int num,String detailedQuery){
		okHttpClient = new OkHttpClient();		
		Request  request = new Request.Builder().url(spaceName+url+"?"+detailedQuery).build();
		okHttpClient.newCall(request).enqueue(new Callback(){

			@Override
			public void onFailure(Request request, IOException e) {

			}

			@Override
			public void onResponse(final Response response) throws IOException {
				// TODO Auto-generated method stub
				if(response.isSuccessful()){
					/**
					 * 限制：返回json字符串需按顺序来，明确前后端数据名称顺序
					 */
					String resultString = response.body().string();
					try {
						JSONObject jsonObject = new JSONObject(resultString);
						generateResultList(jsonObject,num);
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}else{
					throw new IOException("Unexpected code "+response);
				}
				service.setFlag(true);
			}
		});
	}
	
	/**
	 * generate result according to the number of the result
	 * @param resultString the all result from server
	 * @param resultNum specify the amount of the result
	 * @throws JSONException 
	 */
	void generateResultList(JSONObject resultString,int resultNum) throws JSONException{
		result = new ArrayList<String>(resultNum);
		for(int i=0;i<resultNum;i++){
			result.add(resultString.getString(String.valueOf(i+1)));
		}
	}
	
}
